package com.InvoicingSystem.util;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {

	static ThreadLocal<SqlSession> th = new ThreadLocal<SqlSession>();// ThreadLocal
	static SqlSessionFactory sf;

	static {
		try {
			sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatis.xml"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static SqlSession getSession() {
		SqlSession session = th.get();
		if (null == session) {
			session = sf.openSession();
			th.set(session);
		}
		return session;
	}
	

	public static void close() {
		SqlSession session = th.get();
		if (null != session) {
			session.commit();
			session.close();
		}
	}
}
